﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Threading;

namespace Ooganizer.Client.UI
{
    public class LaunchWall
    {
        private static Thread s_thread = null;
        private static bool s_bArtifactWallIsRunning = false;
        private static ArtifactWall s_wArtifactWall = null;
        
        /// <returns>true if ArtifactWall is Running</returns>
        public static bool IsArtifactWallRunning()
        {
            return s_bArtifactWallIsRunning;
        }

        /// <summary>
        /// Message Loop Thread for ArtifactWall
        /// </summary>        
        private static void ThreadProc(object objParam)
        {
            string workspaceName = objParam as string;

            if (workspaceName != null)
            {
                if (s_wArtifactWall == null)
                {
                    s_wArtifactWall = new ArtifactWall(System.Windows.Threading.Dispatcher.CurrentDispatcher, workspaceName);
                    s_bArtifactWallIsRunning = true;
                    s_wArtifactWall.Show();

                    //Enters Message Loop
                    System.Windows.Threading.Dispatcher.Run();
                }
            }
        }
        /// <summary>
        /// Use this to spawn the ArtifactWall Window
        /// </summary>
        public static void SpawnWallThread(string workspaceName)
        {
            if (s_thread != null && s_thread.IsAlive)
            {
                return;
            }
            else
            {
                s_bArtifactWallIsRunning = false;

                // Start a new Thread so it can become the Message Loop
                s_thread = new Thread(LaunchWall.ThreadProc);

                // GUI components require the thread to be STA; otherwise throws an error
                s_thread.SetApartmentState(ApartmentState.STA);
                s_thread.Start(workspaceName);

                // Make sure the Application Object is running
                while (!s_bArtifactWallIsRunning)
                    System.Threading.Thread.Sleep(20); // Syncronous call

                //s_wArtifactWall.Show_ArtifactWallDISP();               
            }
        }
      
        /// <summary>
        /// Use this to kill the ArtifactWall Window
        /// </summary>
        public static void KillWallThread()
        {
            if (s_bArtifactWallIsRunning)
            {
                //s_thread.Abort();
                s_bArtifactWallIsRunning = false;
                s_wArtifactWall = null;
                s_thread = null;
            }
        }
    }
}
